/*
 * Javascript Agile Suite
 * http://code.google.com/p/jasproject/
 *
 * Copyright (C) 2009 Luke Schafer
 * Licensed under MIT X11 license:
 * http://www.opensource.org/licenses/mit-license.php
 */

// Initialise Jas common namespace.
var Jas = Jas || {};
Jas.Exceptions = Jas.Exceptions || { Types : {}};

// Exception Types.
Jas.Exceptions.Types.NOTREGISTERED			= "NotRegisteredException";
Jas.Exceptions.Types.CANTRESOLVE			= "CantResolveException";
Jas.Exceptions.Types.INVALIDARGUMENTS		= "InvalidArgumentsException";
Jas.Exceptions.Types.ASSERTIONEXCEPTION		= "AssertionException";
Jas.Exceptions.Types.IGNORETESTEXCEPTION	= "IgnoreTestException";

// Jas Common functions.

Jas.onLoad = function(handler)
{
	// Same as calling 'window.onload' except this keeps it platform independent.
	// On a platform that doesn't use this, at least it won't break...
	onload = handler;
};

Jas.isFunction = function(obj)
{
	// typeof feels more secure than instanceof, but there's no other real reason for the choice
	return (typeof obj == "function");
};

Jas.extend = function(type, extensions)
{
	extensions = extensions || {};
	for (var i in extensions)
	{
		if(extensions.hasOwnProperty(i))
		{
			type.prototype[i] = extensions[i];
		}
	}
};

Jas.stringFormat = function(str, args)
{
	for (var i = 1; i < arguments.length; i++)
	{
		str = str.replace(new RegExp("[{]" + (i-1) + "[}]", "g"), arguments[i]);
	}
	return str;
};

Jas.Exceptions.create = function(type, message, innerException)
{
	return {
		type : type || "UnknownException",
		message : message || "",
		toString : function() { return Jas.stringFormat("[{0}] {1}", type, message); },
		innerException : innerException || null,
		throwEx : function( inner )
		{	// used as shorthand, but line number will be wrong.
			this.innerException = inner || this.innerException;
			throw(this);
		}
	};
};


// Other Prototypes.

Function.prototype.getInformation = function(func)
{
	func = func || this;

	try
	{
		if (this == Function.prototype && !func) throw("no parameter given to static function");
		var regexp = (/function ([a-z0-9_\-$ ]+)?[(]([a-z0-9_\-$, ]*)[)]\s*{\s*((?:.|\s)*)\s*}/ig);
		var parts = regexp.exec(func.toString());
		parts = parts || regexp.exec(func.toString()); // Hack for firefox
		return {
			name : (parts[1] || "").replace(/\n|\s/g, ""),
			args : parts[2] != "" ? parts[2].replace(/\n|\s/g, "").split(",") : [],
			body : parts[3]
		};
	}
	catch (ex)
	{
		throw(Jas.Exceptions.create(Jas.Exceptions.Types.INVALIDARGUMENTS, "Invalid function declaration", ex));
	}
};